import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { authAPI, User, AuthResponse } from '../services/authAPI'
import { TaskReminderService } from '../services/taskReminder'

interface AuthContextType {
  user: User | null
  loading: boolean
  isLoggedIn: boolean
  
  // 邮箱认证
  registerWithEmail: (email: string, password: string, username?: string) => Promise<AuthResponse>
  loginWithEmail: (email: string, password: string) => Promise<AuthResponse>
  
  // 手机认证
  sendPhoneCode: (phone: string, type?: 'login' | 'register') => Promise<{ success: boolean; message: string; dev_code?: string }>
  loginWithPhone: (phone: string, code: string, username?: string) => Promise<AuthResponse>
  
  // 通用
  logout: () => Promise<void>
  refreshUser: () => Promise<void>
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

interface AuthProviderProps {
  children: ReactNode
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  
  // 组件初始化时检查现有令牌
  useEffect(() => {
    const checkAuthStatus = async () => {
      try {
        if (authAPI.isLoggedIn()) {
          const result = await authAPI.getCurrentUser()
          if (result.success && result.user) {
            setUser(result.user)
            // 用户已登录，启动提醒服务
            TaskReminderService.getInstance().startService()
          } else {
            // 令牌无效，清除
            authAPI.setToken(null)
          }
        }
      } catch (error) {
        console.error('检查认证状态失败:', error)
        authAPI.setToken(null)
      } finally {
        setLoading(false)
      }
    }
    
    checkAuthStatus()
  }, [])



  const registerWithEmail = async (email: string, password: string, username?: string): Promise<AuthResponse> => {
    const result = await authAPI.registerWithEmail(email, password, username)
    
    if (result.success && result.user) {
      setUser(result.user)
    }
    
    return result
  }

  const loginWithEmail = async (email: string, password: string): Promise<AuthResponse> => {
    const result = await authAPI.loginWithEmail(email, password)
    
    if (result.success && result.user) {
      setUser(result.user)
      // 保存JWT令牌
      if (result.token) {
        authAPI.setToken(result.token)
      }
      // 启动提醒服务
      TaskReminderService.getInstance().startService()
    }
    
    return result
  }

  const sendPhoneCode = async (phone: string, type: 'login' | 'register' = 'login') => {
    const result = await authAPI.sendPhoneVerificationCode(phone, type)
    return {
      success: result.success,
      message: result.message,
      dev_code: result.dev_code // 开发环境返回验证码
    }
  }

  const loginWithPhone = async (phone: string, code: string, username?: string): Promise<AuthResponse> => {
    const result = await authAPI.loginWithPhone(phone, code, username)
    
    if (result.success && result.user) {
      setUser(result.user)
      // 保存JWT令牌
      if (result.token) {
        authAPI.setToken(result.token)
      }
      // 启动提醒服务
      TaskReminderService.getInstance().startService()
    }
    
    return result
  }

  const logout = async () => {
    await authAPI.logout()
    authAPI.setToken(null) // 清除令牌
    setUser(null)
    // 停止提醒服务
    TaskReminderService.getInstance().stopService()
  }

  const refreshUser = async () => {
    if (authAPI.isLoggedIn()) {
      const result = await authAPI.getCurrentUser()
      if (result.success && result.user) {
        setUser(result.user)
      }
    }
  }

  const value: AuthContextType = {
    user,
    loading,
    isLoggedIn: !!user,
    registerWithEmail,
    loginWithEmail,
    sendPhoneCode,
    loginWithPhone,
    logout,
    refreshUser
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
